<script setup >
</script>
<template>
    <div >
      <div>
        <el-button  type="primary" @click="handleAddTeacher(teacherFormRef)"  color="#409EFF" style=" color:white;">添加老师</el-button>
      </div>
    <el-table :data="currentTableData" height="480" stripe border class="table">
        <el-table-column prop="name" label="老师" sortable width="180" />
        <el-table-column prop="sex" label="性别" sortable width="180" />
        <el-table-column prop="phone" label="电话号码" sortable width="180" />
        <el-table-column prop="introduce" label="老师介绍" sortable width="180" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" type="primary"  @click="handleEdit(scope.row)" >
            编辑<el-icon><Edit /></el-icon>
            </el-button>
            <el-button size="small" type="primary" color="#23C6C8" style=" color:white;" @click="handleDetail(scope.row)" >
            查看详情<el-icon><Select /></el-icon>
            </el-button>
            <el-button size="small" type="primary" color="#ED5565" style=" color:white;" @click="handleDelete(scope.row)"   >
            删除<el-icon><CloseBold /></el-icon>
            </el-button>
          </template>
        </el-table-column>
    </el-table>

    <div class="pagination-container">
    <el-pagination small background layout="prev, pager, next" :total="totalItems"
            v-model:current-page="currentPage" @current-change="handelCurrentChange" :hide-on-single-page="paginationShow"
            style="margin-top: 20px;" />
    </div>
  </div>
    <el-drawer v-model="drawer" direction="rtl" size="50%">
    <template #header="{ titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">教师管理</h4>
    </template>
          <el-form
              ref="teacherFormRef"
              style="max-width: 600px"
              :model="teacherForm"
              :rules="rules"
              label-width="auto"
              class="add_teacher_form"
              status-icon>
              <el-form-item label="老师姓名" prop="name">
                  <el-input v-model="teacherForm.name" />
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                  <el-input v-model="teacherForm.phone" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                  <el-input v-model="teacherForm.email" />
              </el-form-item>
           
              <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="teacherForm.sex">
                      <el-radio value="男">男</el-radio>
                      <el-radio value="女">女</el-radio>
                  </el-radio-group>
              </el-form-item>

             <el-form-item label="出生日期" prop="birthday" >
                  <el-date-picker v-model="teacherForm.birthday"
                          type="date"
                          aria-label="Pick a date"
                          placeholder="选择日期"
                          style="width: 100%"/>
             </el-form-item>

             <el-form-item label="老师介绍" prop="introduce">
                  <el-input v-model="teacherForm.introduce" type="textarea" />
             </el-form-item>

             <el-form-item>
              
              <div v-if="submit">
                <el-button type="primary" @click="submitForm(teacherFormRef)">
                添加
                </el-button>
                <el-button @click="resetForm(teacherFormRef)">重置</el-button>
              </div>
                
              <div v-else>
                <el-button type="primary" @click="changeForm(teacherFormRef) ">
                保存
              </el-button>
              <el-button @click="outForm(teacherFormRef)">取消</el-button>
              </div>
              
            </el-form-item>

          </el-form>
  </el-drawer>
  
  </template>
  <script lang="ts" setup >



import{ ref , reactive , watch , computed , onMounted, toRaw} from 'vue'
import {  TableColumnCtx} from 'element-plus'
import { ElMessageBox } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import GLOBAL from '@/api/global_variable'
import { handleTeacherSubmit as TeacherApi } from '../../api/teacher'
import { handleTeacherData } from '../../api/teacher'  
import {handleTeacherDelete} from '../../api/teacher'
import { handleTeacherEdit } from '../../api/teacher'
import zhCn from 'element-plus/es/locale/lang/zh-cn'


//import loadJson from  




interface User {
name: string
sex: string
phone: string
introduce: string
email: string
birthday: string

}



const formatter = (row: User, column: TableColumnCtx<User>) => {
return row.phone
}

const tableData= ref([]) 
const tableForm = [
  {value: 'name', label: '姓名'},
  {value: 'sex', label: '性别', width: 100, showOverflowTooltip: true},
  {value: 'phone', label: '手机号', width: 100, showOverflowTooltip: true},
  {value: 'email', label: '邮箱', width: 100, showOverflowTooltip: true},
  {value: 'birthday', label: '出生日期', width: 100, showOverflowTooltip: true},
  {value: 'introduce', label: '备注', width: 100, showOverflowTooltip: true},
]
const currentTableData = ref([])
const currentPage = ref(1)
const pageSize = 10
const totalItems = ref(0)
const paginationShow = ref(true)
const namelist=ref([])


watch(tableData, (newVal, oldVal) => {
    currentPage.value = 1
    totalItems.value = tableData.value.length
    currentTableData.value = tableData.value.filter((item, index) => index < pageSize)
    console.log("开始")
    console.log(currentPage.value)
    console.log(currentTableData.value)
    console.log(totalItems.value)
    console.log(tableData.value)
    console.log("结束")
    paginationShow.value = tableData.value.length > 10 ? true : false
})

const handelCurrentChange = page => {
    currentPage.value = page
    // currentPage.value = 1
    const index = pageSize * (page - 1)
    const nums = pageSize * page
    const tables = []
    for (let i = index; i < nums; i++) {
        if (tableData.value[i]) tables.push(tableData.value[i])
    }
    currentTableData.value = tables
    console.log(currentTableData.value)
}

function handelCurrentChange2 () {
  totalItems.value=tableData.value.length
  const page=Math.ceil(totalItems.value/pageSize)
  console.log(totalItems.value)
  console.log("page="+page)
    currentPage.value = page
    // currentPage.value = 1
    const index = pageSize * (page - 1)
    const nums = pageSize * page
    const tables = []
    for (let i = index; i < nums; i++) {
        if (tableData.value[i]) tables.push(tableData.value[i])
    }
    currentTableData.value = tables
    console.log(currentTableData.value)
}

function handelCurrentChange3 () {
  totalItems.value=tableData.value.length
  if(currentTableData.value.length==0 && currentPage.value!=0){
    GLOBAL.page=currentPage.value-1
  }
  else{
    GLOBAL.page=currentPage.value
  }
  const page=GLOBAL.page
  console.log(totalItems.value)
  console.log("page="+page)
    currentPage.value = page
    // currentPage.value = 1
    const index = pageSize * (page - 1)
    const nums = pageSize * page
    const tables = []
    for (let i = index; i < nums; i++) {
        if (tableData.value[i]) tables.push(tableData.value[i])
    }
    currentTableData.value = tables
    console.log(currentTableData.value)
}

//定义异步方法来加载数据
const getData = async () => {
    try {
        const { data } = await handleTeacherData()
        console.log(data)
        tableData.value = data
        console.log(tableData.value)
        for (let i in tableData.value){
          namelist.value.push(tableData.value[i].name)
        }
    } catch (error) {
        ElMessage.error('请求接口报错')
        console.log(error)
    }
}

onMounted(async () => {
    getData()

}) 

const drawer = ref(false)
const drawerTitle = ref('添加老师')
const submit=ref(true)
function changerules(int){
  if(int==1){
    rules= rules1
  }
  else{
    rules=rules2
  }
}
//给添加按钮添加事件处理，弹出抽屉
const handleAddTeacher = (formElement) => {
    changerules(1)
    drawer.value = true
    drawerTitle.value = '添加老师'
    function funct(){
        submit.value=true
    }
    funct()
    teacherForm.name = null
    teacherForm.phone = null
    teacherForm.email= null
    teacherForm.introduce=null
    teacherForm.birthday=null
    teacherForm.sex=null
}


//以下是在抽屉里的按钮添加的事件和表单验证相关的操作
const teacherFormRef = ref()

const namerules = (rule: any, value: any, callback: any) => {
  console.log("已调用")
  console.log(namelist.value[0])
  console.log(teacherForm.name)
  if (namelist.value.indexOf(teacherForm.name) != -1) {

    console.log("!问题!")
        callback(new Error("老师姓名重复"))
      }
  else{
    console.log("没问题")
    callback()
  }
}
const namerules2 = (rule: any, value: any, callback: any) => {
  console.log("已调用")
  console.log(namelist.value[0])
  console.log(teacherForm.name)
  if (namelist.value.indexOf(teacherForm.name) == -1) {
    console.log("!问题!")
        callback(new Error("老师姓名不存在"))
      }
  else{
    console.log("没问题")
    callback()
  }
}
const teacherForm = reactive({
    name: '',
    phone: '',
    email: '',
    sex: '',
    birthday: '',
    introduce: '',
})
const rules1 = reactive({
  name: [
  {validator: namerules, trigger: ['change','blur']},
    { required: true, message: '请输入老师姓名', trigger: 'blur' },
    { min: 1, max: 6, message: '姓名长度在1-6之间', trigger: 'blur' },
    
  ],
  phone: [
    {
      required: true,
      message: '请输入手机号码',
      trigger: 'blur',
    },
    { pattern: /\d{11}$/, message: '请输入正确的手机号码', trigger: ['blur', 'change']},
  ],
  sex: [
    {
        required: true,
        message: '请选择性别',
        trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur',
      type:'email',
    },
  ],
  birthday: [
    {
      type: 'date',
      required: true,
      message: '请选择生日',
      trigger: 'change',
    },
  ],
  introduce: [
    { required: false, message: '自我介绍', trigger: 'blur' },
  ],
})
const rules2=reactive({
  name: [
  {validator: namerules2, trigger: ['change','blur']},
    { required: true, message: '请输入老师姓名', trigger: 'blur' },
    { min: 1, max: 6, message: '姓名长度在1-6之间', trigger: 'blur' },
    
  ],
  phone: [
    {
      required: true,
      message: '请输入手机号码',
      trigger: 'blur',
    },
    { pattern: /\d{11}$/, message: '请输入正确的手机号码', trigger: ['blur', 'change']},
  ],
  sex: [
    {
        required: true,
        message: '请选择性别',
        trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur',
      type:'email',
    },
  ],
  birthday: [
    {
      type: 'date',
      required: true,
      message: '请选择生日',
      trigger: 'change',
    },
  ],
  introduce: [
    { required: false, message: '自我介绍', trigger: 'blur' },
  ],
})
let rules=rules2


//提交和重置函数
const submitForm = async (formElement) => {

    console.log(formElement)

    if (!formElement) return
    //进行验证
    await formElement.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            // todo 这里去提交表单数据到后端
            TeacherApi(teacherForm).then(res=>{
                console.log("这也是返回值"+res.status)
                if(res.status==200){
                  drawer.value = false
                  tableData.value.push({name:teacherForm.name,sex:teacherForm.sex,
                    phone:teacherForm.phone,introduce:teacherForm.introduce,email:teacherForm.email,birthday:teacherForm.birthday})
                    currentTableData.value.push({name:teacherForm.name,sex:teacherForm.sex,
                      phone:teacherForm.phone,introduce:teacherForm.introduce,email:teacherForm.email,birthday:teacherForm.birthday})

                      handelCurrentChange2 ()
                  namelist.value.push(teacherForm.name)
                  console.log(teacherForm)
                  console.log(tableData.value)
                  console.log(currentTableData.value)
                  ElMessageBox.alert('添加成功！', '添加成功', {
                      type: 'success',
                      center:true,
                  })
                }
                else{
                    ElMessageBox.alert('添加失败！', '添加失败', {
                        type: 'error',
                    })
                }
            })
            // ...

        } else {
            console.log('表单验证失败，请重新填写', fields)
        }
    })
}
//重置表单，这里不传参数也可以，因为我们定义了 teacherFormRef 对象
const resetForm = () => {
    teacherForm.name = null
    teacherForm.phone = null
    teacherForm.email= null
    teacherForm.introduce=null
    teacherForm.birthday=null
    teacherForm.sex=null
}
const handleDelete = (row: User) => {
  changerules(2)
  ElMessageBox.confirm(
    
    '确认删除此老师信息吗?删除成功后将无法恢复，请谨慎操作！',
    '删除确认',
    {
    dangerouslyUseHTMLString: true,
      type: 'warning',
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      center:true,
      
    }
  )
  .then(() => {
    const index2 = currentTableData.value.indexOf(row);
    const index = index2+(currentPage.value-1)*pageSize;
    console.log("这是row"+row)
    console.log("这是index"+index)
    console.log("这是index2"+index2)
    handleTeacherDelete(row).then(res=>{
                console.log("这是返回值"+res.status)
                if(res.status==200){
                  if (index !== -1 && index2 !== -1) {
                    tableData.value.splice(index, 1);
                    namelist.value.splice(index, 1);
                    currentTableData.value.splice(index2, 1);
                    handelCurrentChange3();
                    drawer.value=false
                    ElMessageBox.alert('删除成功！', '删除成功', {
                    type: 'success',
                    center:true,
                    })
                  }
                  else{
                    ElMessageBox.alert('删除失败！', '删除失败', {
                    type: 'error',
                    center:true,
                    })
                  }
                }
                else{
                  ElMessageBox.alert('删除失败！', '删除失败', {
                      type: 'error',
                      center:true,
                  })
                }
            })
  })
}

const router = useRouter()
const handleDetail = (row) => {
    //进行编程式导航
    const index2 = currentTableData.value.indexOf(row);
    const index = index2+(currentPage.value-1)*pageSize;
    const params = {index: `${index}`}
    console.log("这是index"+index)
    router.push({
        name: 'TeacherDetail',
        state:{params}
    }) 
   
}
const handleEdit = (row:User) => {
  changerules(2)
  console.log(rules)
    //修改抽屉title
    drawerTitle.value = '修改老师'
    //打开抽屉
    drawer.value = true

    function funct(){
        submit.value=false
    }
    funct()
    //给表单元素赋值
    teacherForm.name = row.name
    teacherForm.phone = row.phone
    teacherForm.email= row.email
    teacherForm.introduce=row.introduce
    teacherForm.birthday=row.birthday
    teacherForm.sex=row.sex
    //todo ...
    GLOBAL.index=tableData.value.indexOf(row);
}

const changeForm = async (formElement,row:User) => {
    console.log(formElement)

    if (!formElement) return
    //进行验证
    await formElement.validate((valid, fields) => {
        if (valid) {
            console.log('change!')
            console.log(row)
            console.log(tableData)
            
            // todo 这里去提交表单数据到后端
            handleTeacherEdit(teacherForm).then(res=>{
                console.log(res)
                if(res.status==200){
                  drawer.value = false
                  tableData.value.splice(GLOBAL.index,1,{name:teacherForm.name,sex:teacherForm.sex,
                    phone:teacherForm.phone,introduce:teacherForm.introduce,email:teacherForm.email,birthday:teacherForm.birthday})
                  currentTableData.value.splice(Math.ceil(GLOBAL.index%pageSize),1,{name:teacherForm.name,sex:teacherForm.sex,
                    phone:teacherForm.phone,introduce:teacherForm.introduce,email:teacherForm.email,birthday:teacherForm.birthday})
                  ElMessageBox.alert('修改成功！', '修改成功', {
                        type: 'success',
                        center:true,
                    })
                }
                else{
                    ElMessageBox.alert('修改失败！', '修改失败', {
                        type: 'error',
                    })
                }
            })
            // ...

        } else {
            console.log('表单验证失败，请重新填写', fields)
        }
    })
}

const outForm = (formElement) => {

  const row=tableData.value[GLOBAL.index]
  teacherForm.name = row.name
    teacherForm.phone = row.phone
    teacherForm.email= row.email
    teacherForm.introduce=row.introduce
    teacherForm.birthday=row.birthday
    teacherForm.sex=row.sex
}
 

  </script>

<style scoped>
    .pagination-container {
        margin-top: 15px;
        display: flex;
        justify-content: flex-end;
    }

    .add_teacher_form {
        margin: 10px 50px;
    }
</style>